package thread;

/**
 *  互斥锁
 *  当使用synchronized锁定多个不同的代码片段,并且指定的同步监视器对象相同时,这些代码片段之间就是互斥的,
 *  即:多个线程不能同时访问这些方法.
 */
public class SyncDemo4 {
    public static void main(String[] args) {
        Foo foo = new Foo();
        Thread t1 = new Thread(){
            public void run(){
                foo.methodA();
            }
        };
        Thread t2 = new Thread(){
            public void run(){
                foo.methodB();
            }
        };
        t1.start();
        t2.start();
    }
}

class Foo{
    public void methodA(){
        synchronized(this) {
            Thread t = Thread.currentThread();
            try {
                System.out.println(t.getName() + ":正在执行A方法");
                Thread.sleep(5000);
                System.out.println(t.getName() + ":执行A方法完毕");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public synchronized void methodB(){
        Thread t = Thread.currentThread();
        try {
            System.out.println(t.getName()+":正在执行B方法");
            Thread.sleep(5000);
            System.out.println(t.getName()+":执行B方法完毕");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}